#!/bin/sh

# Copyright (C) 2008, Arthur Furlan <arthur.furlan@gmail.com>
# Copyright (C) 2008, Felipe Augusto van de Wiel <faw@funlabs.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

PROGRAM_NAME=$(basename $0)
LOGBOOK_FILE="$HOME/LogBook"
CONFIG_FILE="$HOME/.logbook"
DCH_ARGS=

confirm_root() {
    if [[ "$USER" == "root" ]]; then
        echo "You're not supposed to use the $PROGRAM_NAME as $USER user."
        OPTION=
        while [[ "$OPTION" != 'y' && "$OPTION" != 'n' ]]; do
            read -p "Do you want to continue? [y/n] " OPTION
        done
        if [[ "$OPTION" = 'n' ]]; then
            exit
        fi
    fi
}

create_config() {
    echo "LOGBOOK_FILE=$LOGBOOK_FILE"   >  $CONFIG_FILE
    echo "AUTO_COMMIT=1"                >> $CONFIG_FILE
    echo "AUTO_UPDATE=1"                >> $CONFIG_FILE
}

load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        . "$CONFIG_FILE"
    fi
}

svn_auto_update() {
    if [[ -z "$CREATE_LOGBOOK_FILE" && "$AUTO_UPDATE" == 1 ]]; then
        svn up "$LOGBOOK_FILE" > /dev/null
    fi
}

svn_auto_commit() {
    if [[ -z "$CREATE_LOGBOOK_FILE" && "$AUTO_COMMIT" == 1 ]]; then
        svn ci "$LOGBOOK_FILE" -m "[LogBook] Auto-commit: version $1" > /dev/null
    fi
}

load_config

NEW_VERSION=$(date +%Y%m%d)

while getopts 'c:V:vhiIuU' OPTION; do
    case $OPTION in

        c) # create LOGBOOK_FILE
            CREATE_LOGBOOK_FILE=1
            LOGBOOK_FILE="$OPTARG"
            DCH_ARGS="$DCH_ARGS --create $LOGBOOK_FILE"
        ;;

        u) # auto-update enable
            AUTO_UPDATE=1
        ;;

        U) # auto-update disable
            AUTO_UPDATE=0
        ;;

        i) # auto-commit enable
            AUTO_COMMIT=1
        ;;

        I) # auto-commit disable
            AUTO_COMMIT=0
        ;;

        v) # show the current version
            echo "$PROGRAM_NAME: version 0.01"
            exit 0
        ;;

        V) # new version
            NEW_VERSION="$OPTARG"
        ;;

        h|?) # display the usage
            echo "Usage: $PROGRAM_NAME [-i|-I] [-u|-U] [-v] [-h] [-V VERSION] [-c LOGBOOK_FILE]" >&2
            exit 2
        ;;

    esac
done

confirm_root
if [[ -z "$CREATE_LOGBOOK_FILE" ]]; then
    if [[ ! -f "$LOGBOOK_FILE" ]]; then
        echo "$PROGRAM_NAME: $LOGBOOK_FILE: No such file or directory"
        exit 1;
    fi

    svn_auto_update
    CUR_VERSION=$(head -n 1 $LOGBOOK_FILE | sed 's/^.*\([0-9]\{8\}\).*$/\1/')

    if [[ -z $CUR_VERSION || $CUR_VERSION != $NEW_VERSION ]]; then
        dch $DCH_ARGS --multimaint -c $LOGBOOK_FILE -v $NEW_VERSION
    else
        dch $DCH_ARGS --multimaint -a -c $LOGBOOK_FILE
    fi
else
    create_config
    dch $DCH_ARGS --multimaint -c $LOGBOOK_FILE -v $NEW_VERSION
fi

svn_auto_commit $NEW_VERSION
